# -*- coding: utf-8 -*-
"""
demo.py
"""
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import os
from tornado.options import define, options
define("port", default=8003, help="run on the given port", type=int)

from wxtest import Group, Friend, TEXT, run

# bot = run()

def reset_file(path):
	"""重置文件是否存在"""
	with open(path, 'w') as f:
		f.write('')

path_u = os.path.join(os.path.dirname(__file__), 'static\img\login_status.txt')
path_l = os.path.join(os.path.dirname(__file__), 'static\img\uuid.txt')

reset_file(path_u)
reset_file(path_l)

class MainHandler(tornado.web.RequestHandler):
	def get(self):
		f_msg = self.get_argument('friend', '')
		g_msg = self.get_argument('group', '')
		puid = self.get_argument('puid', '')
		groups = bot.groups()
		friends = bot.friends()
		
		if f_msg:
			puid = puid or '27bbe5a2'
			for f in friends:
				if f.puid == puid:
					break
			f.send(f_msg)
			self.write(u'发消息给>>>%s: %s<br>' % (f.nick_name, f_msg))
		if g_msg:
			puid = puid or '982c10f5'
			for g in groups:
				if g.puid == puid:
					break
			g.send(g_msg)
			self.write(u'发消息给>>>%s: %s<br>' % (g.nick_name, g_msg))
					
		# member_str = '<br>'.join(['%s%s%s' % (g.nick_name, '&nbsp;'*20, member.nick_name) for member in g])
		# self.write(member_str)
		g_str = '<br>'.join(['%s%s%s' % (g.puid, '&nbsp;'*20, g.nick_name) for g in groups])

		self.write('<br>'*5)
		self.write(g_str)


class IndexHandler(tornado.web.RequestHandler):
	def get(self):
		login = self.get_argument('login', '')
		if login:
			bot = run()
			groups = bot.groups()
			puid = '579d26a8'
			for g in groups:
				if g.puid == puid:
					break
			self.render(
				"index.html",
				page_title="WebChat",
				group = g
				)
		else:
			self.write(u'机器人没有启动')


if __name__ == "__main__":
	handlers_list = [
		# (r"/", MainHandler),
		(r"/", IndexHandler), 
		]
	tornado.options.parse_command_line()
	settings = dict(
	    template_path=os.path.join(os.path.dirname(__file__), "templates"),
	    static_path=os.path.join(os.path.dirname(__file__), "static"),
	    debug=True,
	)
	app = tornado.web.Application(handlers=handlers_list, **settings)
	http_server = tornado.httpserver.HTTPServer(app)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()

"""
python demo.py --port=8881
end demo.py
"""